package com.example.spring_java_oj.mapper;

import com.example.spring_java_oj.model.UserInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component
public class UserInfoRedis {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 根据用户名, 查询用户信息
     */
    public UserInfo getUserInfoByName(String username) throws JsonProcessingException {
        String json = (String) stringRedisTemplate.opsForHash().get("userByName", username);
        UserInfo userInfo = null;
        if(json != null){
            userInfo = objectMapper.readValue(json, UserInfo.class);
        }
        return userInfo;
    }


    /**
     * 根据用户ID, 查询用户信息
     */
    public UserInfo getUserInfoById(Integer id) throws JsonProcessingException {
        String json = (String) stringRedisTemplate.opsForHash().get("userById", Integer.toString(id));
        UserInfo userInfo = null;
        if(json != null){
            userInfo = objectMapper.readValue(json, UserInfo.class);
        }
        return userInfo;
    }

    /**
     * 注册用户
     */
    public void register(UserInfo userInfo) throws JsonProcessingException {
        String json = objectMapper.writeValueAsString(userInfo);
        stringRedisTemplate.opsForHash().put("userByName", userInfo.getUserName(), json);
        stringRedisTemplate.opsForHash().put("userById", Integer.toString(userInfo.getId()), json);
    }

}
